package com.example.xinhuazidian.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.example.xinhuazidian.R
import com.example.xinhuazidian.bean.Paragraphs
import com.google.gson.Gson

class QianjiashiXiangqingAdapter(private val list: MutableList<Any>) :
    RecyclerView.Adapter<QianjiashiXiangqingAdapter.MyViewHolder>() {

    inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val tvSubchapter: TextView = view.findViewById(R.id.tvSubchapter)
        val rv: RecyclerView = view.findViewById(R.id.rv)
        val v: View = view.findViewById(R.id.v)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val view =
            LayoutInflater.from(parent.context)
                .inflate(R.layout.item_qianjiashi_xiangqing, parent, false)
        return MyViewHolder(view)
    }

    @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val list = list[position]
        with(holder) {
            val type = Gson().toJson(list).substring(0, 1)
            if ("{" == type) {
                v.visibility = View.GONE

                val paragraphs = Gson().fromJson(Gson().toJson(list), Paragraphs::class.java)

                tvSubchapter.text = paragraphs.subchapter
                val staggeredGridLayoutManager =
                    StaggeredGridLayoutManager(1, LinearLayoutManager.VERTICAL)
                rv.layoutManager = staggeredGridLayoutManager
                //加载适配器
                val szjAdapter = SZJAdapter(paragraphs.paragraphs)
                rv.adapter = szjAdapter
            } else {
                v.visibility = View.VISIBLE
                tvSubchapter.text = list.toString()
            }
        }
    }

    override fun getItemCount() = list.size
}
